<template>
  <div class="checkin-record-list">
    <el-card class="checkin-record-card">
      <template #header>
        <div class="card-header">
          <span>签到记录列表</span>
          <div class="header-actions">
            <el-date-picker
              v-model="searchForm.date"
              type="date"
              placeholder="选择日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 150px; margin-right: 10px"
              @change="handleSearch"
            />
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入会员姓名"
              style="width: 200px; margin-right: 10px"
              clearable
              @clear="handleSearch"
              @keydown.enter="handleSearch"
            >
              <template #append>
                <el-button icon="Search" @click="handleSearch" :loading="loading" />
              </template>
            </el-input>
            <el-button @click="handleExport">导出记录</el-button>
          </div>
        </div>
      </template>

      <!-- 签到统计信息 -->
      <el-row :gutter="20" style="margin-bottom: 20px;">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">总签到次数</div>
              <div class="stat-value">{{ statistics.totalCheckins }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">今日签到</div>
              <div class="stat-value">{{ statistics.todayCheckins }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">签到会员数</div>
              <div class="stat-value">{{ statistics.memberCount }}</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-item">
              <div class="stat-label">日均签到</div>
              <div class="stat-value">{{ statistics.avgDailyCheckins }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-table
        :data="checkinRecordList"
        v-loading="loading"
        style="width: 100%"
        row-key="id"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="memberName" label="会员姓名" width="120" />
        <el-table-column prop="checkinTime" label="签到时间" width="180" />
        <el-table-column prop="checkinType" label="签到方式" width="120">
          <template #default="scope">
            <el-tag :type="getCheckinTypeTagType(scope.row.checkinType)">
              {{ formatCheckinType(scope.row.checkinType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="location" label="签到位置" show-overflow-tooltip />
        <el-table-column prop="deviceInfo" label="设备信息" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '有效' : '无效' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180" />
      </el-table>

      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 会员签到对话框 -->
    <el-dialog
      v-model="checkinDialogVisible"
      title="会员签到"
      width="500px"
    >
      <el-form
        ref="checkinFormRef"
        :model="checkinForm"
        :rules="checkinRules"
        label-width="100px"
      >
        <el-form-item label="会员" prop="memberId">
          <el-select
            v-model="checkinForm.memberId"
            placeholder="请选择会员"
            style="width: 100%"
            filterable
          >
            <el-option
              v-for="member in memberList"
              :key="member.id"
              :label="`${member.name} (${member.phone})`"
              :value="member.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="签到方式" prop="checkinType">
          <el-radio-group v-model="checkinForm.checkinType">
            <el-radio :label="1">二维码签到</el-radio>
            <el-radio :label="2">地理位置签到</el-radio>
          </el-radio-group>
        </el-form-item>
        <div v-if="checkinForm.checkinType === 1">
          <el-form-item label="二维码内容" prop="qrCode">
            <el-input v-model="checkinForm.qrCode" placeholder="请输入二维码内容" :maxlength="200" show-word-limit />
          </el-form-item>
        </div>
        <div v-if="checkinForm.checkinType === 2">
          <el-form-item label="纬度" prop="latitude">
            <el-input-number
              v-model="checkinForm.latitude"
              :precision="6"
              :step="0.000001"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="经度" prop="longitude">
            <el-input-number
              v-model="checkinForm.longitude"
              :precision="6"
              :step="0.000001"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="位置描述" prop="location">
            <el-input v-model="checkinForm.location" placeholder="请输入位置描述" :maxlength="200" show-word-limit />
          </el-form-item>
        </div>
        <el-form-item label="设备信息" prop="deviceInfo">
          <el-input
            v-model="checkinForm.deviceInfo"
            type="textarea"
            :rows="2"
            placeholder="请输入设备信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="checkinDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCheckinSave" :loading="checkinLoading">签到</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import type {
  CheckinRecord,
  QRCodeCheckinRequest,
  LocationCheckinRequest,
  CheckinStatistics
} from '@/types/api/checkin'
import type { Member } from '@/types/api/member'
import { checkinApi } from '@/api/modules/checkin'
import { memberApi } from '@/api/modules/member'
import { preventDuplicateSubmit } from '@/utils'

// 表格相关
const loading = ref(false)
const checkinRecordList = ref<CheckinRecord[]>([])
const searchForm = reactive({
  keyword: '',
  date: ''
})

// 分页相关
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 统计信息
const statistics = ref<CheckinStatistics>({
  totalCheckins: 0,
  todayCheckins: 0,
  memberCount: 0,
  avgDailyCheckins: 0
})

// 对话框相关
const checkinDialogVisible = ref(false)
const checkinLoading = ref(false)
const checkinFormRef = ref()

// 下拉列表数据
const memberList = ref<Member[]>([])

// 表单数据
const checkinForm = reactive({
  memberId: undefined as number | undefined,
  checkinType: 1, // 默认二维码签到
  qrCode: '',
  latitude: 0,
  longitude: 0,
  location: '',
  deviceInfo: ''
})

// 表单验证规则
const checkinRules = {
  memberId: [
    { required: true, message: '请选择会员', trigger: 'change' }
  ],
  qrCode: [
    { required: true, message: '请输入二维码内容', trigger: 'blur' }
  ],
  latitude: [
    { required: true, message: '请输入纬度', trigger: 'blur' }
  ],
  longitude: [
    { required: true, message: '请输入经度', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入位置描述', trigger: 'blur' }
  ]
}

// 获取签到方式标签类型
const getCheckinTypeTagType = (checkinType: number) => {
  switch (checkinType) {
    case 1: return 'success' // 二维码签到
    case 2: return 'warning' // 地理位置签到
    default: return 'info'
  }
}

// 格式化签到方式显示
const formatCheckinType = (checkinType: number) => {
  switch (checkinType) {
    case 1: return '二维码签到'
    case 2: return '地理位置签到'
    default: return '未知'
  }
}

// 获取签到记录列表
const getCheckinRecordList = async () => {
  loading.value = true
  try {
    const response = await checkinApi.getCheckinRecordList({
      page: pagination.page,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      date: searchForm.date
    })
    checkinRecordList.value = response.data.data.list
    pagination.total = response.data.data.total
  } catch (error) {
    ElMessage.error('获取签到记录列表失败')
  } finally {
    loading.value = false
  }
}

// 获取签到统计信息
const getCheckinStatistics = async () => {
  try {
    const response = await checkinApi.getCheckinStatistics({})
    statistics.value = response.data.data
  } catch (error) {
    ElMessage.error('获取签到统计信息失败')
  }
}

// 获取会员列表
const getMemberList = async () => {
  try {
    const response = await memberApi.getMemberList({
      page: 1,
      pageSize: 1000 // 获取所有会员
    })
    memberList.value = response.data.data.list
  } catch (error) {
    ElMessage.error('获取会员列表失败')
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  getCheckinRecordList()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val
  pagination.page = 1
  getCheckinRecordList()
}

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.page = val
  getCheckinRecordList()
}

// 导出记录
const handleExport = () => {
  ElMessage.info('导出功能待实现')
}

// 会员签到
const handleMemberCheckin = () => {
  checkinDialogVisible.value = true
  // 重置表单
  Object.assign(checkinForm, {
    memberId: undefined,
    checkinType: 1,
    qrCode: '',
    latitude: 0,
    longitude: 0,
    location: '',
    deviceInfo: ''
  })
  // 获取会员列表
  getMemberList()
}

// 保存签到信息
const handleCheckinSave = async () => {
  if (!checkinFormRef.value) return

  await checkinFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      // 使用防重复提交保护
      await preventDuplicateSubmit('member_checkin', async () => {
        checkinLoading.value = true
        try {
          if (checkinForm.checkinType === 1) {
            // 二维码签到
            const qrCodeData: QRCodeCheckinRequest = {
              memberId: checkinForm.memberId!,
              qrCode: checkinForm.qrCode,
              deviceInfo: checkinForm.deviceInfo
            }
            await checkinApi.qrCodeCheckin(qrCodeData)
            ElMessage.success('二维码签到成功')
          } else {
            // 地理位置签到
            const locationData: LocationCheckinRequest = {
              memberId: checkinForm.memberId!,
              latitude: checkinForm.latitude,
              longitude: checkinForm.longitude,
              location: checkinForm.location,
              deviceInfo: checkinForm.deviceInfo
            }
            await checkinApi.locationCheckin(locationData)
            ElMessage.success('地理位置签到成功')
          }
          checkinDialogVisible.value = false
          getCheckinRecordList()
          getCheckinStatistics()
        } catch (error: any) {
          ElMessage.error('签到失败')
          throw error // 重新抛出错误以确保防重复提交正确处理
        } finally {
          checkinLoading.value = false
        }
      })
    }
  })
}

// 初始化
onMounted(() => {
  getCheckinRecordList()
  getCheckinStatistics()
})
</script>

<style scoped lang="scss">
.checkin-record-list {
  .checkin-record-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    .stat-card {
      .stat-item {
        text-align: center;

        .stat-label {
          font-size: 14px;
          color: #606266;
          margin-bottom: 10px;
        }

        .stat-value {
          font-size: 20px;
          font-weight: bold;
          color: #303133;
        }
      }
    }

    .pagination {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
